package com.taoym.voucher.xcx.service.impl;

import com.taoym.voucher.common.response.ResponseStatusCode;
import com.taoym.voucher.common.utils.ExceptionCore;
import com.taoym.voucher.xcx.service.RedisService;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.LinkedList;

/**
 * @coder taoym
 * @datetime 2021/9/23 23:04
 * @desc
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public Long generateIncrementOneUID(String key) {
        RedisAtomicLong redisAtomicLong = getRedisAtomicLong(key);
        return redisAtomicLong.addAndGet(1);
    }

    @Override
    public LinkedList<Long> generateIncrementOneUIDBatch(String key, Integer size) {
        RedisAtomicLong redisAtomicLong = getRedisAtomicLong(key);
        LinkedList<Long> IDS = new LinkedList<>();
        long max = redisAtomicLong.addAndGet(size);
        for (int i = 0; i < size; i++) {
            IDS.push(max - i);
        }
        return IDS;
    }

    private RedisAtomicLong getRedisAtomicLong(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, getRedisConnectionFactory());
        if (redisAtomicLong.get() == 0) {
            redisAtomicLong.set(10000L);
        }
        return redisAtomicLong;
    }

    private RedisConnectionFactory getRedisConnectionFactory() {
        RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory();
        if (ObjectUtils.isEmpty(connectionFactory)) {
            throw new ExceptionCore(ResponseStatusCode.REDIS_CONNECTION_FACTORY_IS_FAIL);
        }
        return connectionFactory;
    }
}
